package com.cloudfun.msglisten.ws.haier.handler;

import com.alibaba.fastjson.JSONObject;
import com.cloudfun.msglisten.common.constant.RabbitConstants;
import com.cloudfun.msglisten.common.constant.SysDictType;
import com.cloudfun.msglisten.service.SysDictService;
import com.cloudfun.msgsubscribe.DeviceInfo;
import com.cloudfun.msgsubscribe.Topic;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * Created by Huqin on 2020/3/30
 */
@Slf4j
@Component
public class DeviceAttrMsgHandler extends AbstractDeviceMsgHandler {

    @Autowired
    private SysDictService sysDictService;

    @Override
    public boolean canHandle(String topicName) {
        return "attr".equals(topicName);
    }

    @Override
    protected void doHandle(JSONObject jsonObject, DeviceInfo deviceInfo, String appId) {
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if (StringUtils.isBlank(entry.getKey())) {
                continue;
            }
            deviceInfo.setAttr(entry.getKey(), entry.getValue().toString());
        }
        if (!deviceInfo.emptyAttrs()) {
            // 发往外部
            this.sendToExternal(appId, deviceInfo);
            // 内部广播
            rabbitTemplate.convertAndSend(RabbitConstants.Exchange.DEVICE_STATUS, "", deviceInfo);
            // ws
//            remoteMessageService.sendMsg(Topic.STATUS, deviceInfo);
        }
    }

    private void sendToExternal(String appId, DeviceInfo deviceInfo) {
        DeviceInfo tmp = new DeviceInfo();
        tmp.setImei(deviceInfo.getImei());
        tmp.setTimestamp(deviceInfo.getTimestamp());
        Map<String, String> availablePropMap = sysDictService.getDictByType(SysDictType.AVAILABLE_DEVICE_PROPERTY);
        Set<String> availablePropNames = availablePropMap.keySet();
        for (Map.Entry<String, String> entry : deviceInfo.getAttrs().entrySet()) {
            if (availablePropNames.contains(entry.getKey())) {
                tmp.setAttr(entry.getKey(), entry.getValue());
            }
        }
        if (tmp.emptyAttrs()) {
            return;
        }
        // 发往外部
        log.info("2G设备消息：{}发送到外部：{}", tmp, appId);
        externalRabbitTemplate.convertAndSend(RabbitConstants.Exchange.DEVICE_STATUS, appId, tmp);
    }
}
